package com.yfp.org.mq;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.google.gson.Gson;
import com.yfp.common.core.utils.uuid.Snowflake;
import com.yfp.org.domain.entity.*;
import com.yfp.org.mapper.*;
import com.yfp.org.service.OrderComboService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Value;

import java.util.*;

// @Component
@Slf4j
// @RocketMQMessageListener(topic = "DataSyn", consumerGroup = "orderBackground")
public class MQConsumerService implements RocketMQListener<String> {

    @Resource
    private OrderListMapper orderListMapper;

    @Resource
    private MachineMapper machineMapper;

    @Value("${MiniProgram.OrderUrl}")
    private String orderUrl;

    @Resource
    CompanyMapper companyMapper;

    @Resource
    private OrderComboService orderComboService;

    @Resource
    private ComboMapper comboMapper;

    @Resource
    private TagComboMapper tagComboMapper;

    @Resource
    private AreaMapper areaMapper;

    @Resource
    private PositionMapper positionMapper;

    @Resource
    private RouteMapper routeMapper;
    @Resource
    private MqConsumerMapper mqConsumerMapper;



    @Override
    public void onMessage(String message) {
        log.info("ROCKETMQ收到消息：{}", message);
        // 实现消息处理逻辑
        processMessage(message);
    }

    // 消息处理方法
    private void processMessage(String message) {
        Map parse = (Map) JSON.parse(message);
        Result result = JSON.parseObject(JSON.toJSONString(parse), Result.class);
        Map map = (Map) JSON.parse(result.getMsgData());
        Result msgResult = JSON.parseObject(JSON.toJSONString(map), Result.class);
        log.info("查询id:{}",result.getMsgId());


        long l = mqConsumerMapper.queryById(result.getMsgId());
        log.info("查询结果:{}",l);

        if (l>0){
            log.info("重复消息:{}",message);
            return;
        }


        MqConsumer mqConsumer = new MqConsumer();
        mqConsumer.setId(result.getMsgId());
        mqConsumer.setMsg(message);
        log.info("数据添加通过");
        mqConsumerMapper.insertMq(mqConsumer);
        String msgType = result.getMsgType();
        log.info("收到Order消息类型：{}", msgType);

        if (Objects.equals(MqResultMsgType.CREATE.getKey(), msgType)) {
            log.info("正在处理创建信息：{}", msgType);

            createMiniProgramOrder(msgResult);
        } else if (Objects.equals(MqResultMsgType.UPDATE.getKey(), msgType)) {
            log.info("正在处理修改信息：{}", msgType);

            updateMiniProgramOrder(msgResult);
        } else {
            log.error("消息类型不匹配，无法处理");
        }

    }

    /**
     * 更新小程序订单状态
     *
     * @param msgResult 消息结果
     */
    private void updateMiniProgramOrder(Result msgResult) {

        String applyTime = msgResult.getApplyTime();
        if (CharSequenceUtil.isNotEmpty(applyTime)) { //不为空,都是退款的订单消息
            //更新订单退款时间   用户主动申请退款
            DateTime date =DateUtil.parseUTC(applyTime);
            OrderCombo order = msgResult.getOrder();
            OrderList orderList1 = new OrderList();
            orderList1.setOrderSn(order.getOrderId());
            OrderList orderList = orderListMapper.queryById(orderList1);
            if (Objects.isNull(orderList)) {
                log.info("订单号:{},未查询到相关订单信息", order.getOrderId());
                return;
            }
            //退款时间为空 请求小程序接口获取退款时间
            getMiniProgramRefundInformation(order.getOrderId());
            log.info("订单号:{},退款时间:{}退款时间更新成功", order.getOrderId(), DateUtil.formatDateTime(date));
        }else{
            log.info("订单处理");
            updateOrderStatus(msgResult);
        }
    }

    private void updateOrderStatus(Result msgResult) {

        OrderList orderList1 = new OrderList();

        orderList1.setOrderSn(msgResult.getOrder().getOrderId());

        OrderList orderList = orderListMapper.queryById(orderList1);

        if (Objects.isNull(orderList)) {
            log.error("订单号:{},未查询到相关订单信息", msgResult.getOrder().getOrderId());
            return;
        }
        if (msgResult.getPaymentMethods()!=null){

            switch (msgResult.getPaymentMethods()){
                case "WeChatPay":
                    orderList1.setPayType("2");
                    break;
                case "Alipay":
                    orderList1.setPayType("1");
                    break;
                default:
                    log.error("订单号:{},支付方式不匹配", msgResult.getOrder().getOrderId());
                    break;
            }
            }
        switch (msgResult.getOrder().getStatus()) {

            case "Canceled":
                orderList1.setPayStatus(OrderStatus.Canceled.getCode());
                orderList1.setUpdateTime(new Date());
                break;
            case "Refund":
                orderList1.setPayStatus(OrderStatus.Refund.getCode());
                orderList1.setUpdateTime(new Date());
                break;
            case "AwaitPackage":
                orderList1.setPayStatus(OrderStatus.AwaitPackage.getCode());
                orderList1.setPayTime(DateUtil.parseUTC(msgResult.getPayTime()));
                orderList1.setUpdateTime(new Date());
                log.info("修改数据");
                break;
            case "Finish":
                orderList1.setPayStatus(OrderStatus.Finish.getCode());
                orderList1.setPayTime(DateUtil.parseUTC(msgResult.getPayTime()));
                orderList1.setUpdateTime(new Date());
                break;
            default:
                log.error("订单号:{},订单状态不匹配", msgResult.getOrder().getOrderId());
                break;
        }

        orderListMapper.update(orderList1);
    }


    private void getMiniProgramRefundInformation(String orderId) {
        OrderList orderList1 = new OrderList();
        orderList1.setOrderSn(orderId);
        OrderList orderList = orderListMapper.queryById(orderList1);

        if (Objects.isNull(orderList)) {
            log.info("订单号:{},未查询到相关订单信息", orderId);
            return;
        }
        Snowflake snowflake = new Snowflake(1);
        String refundSn = String.valueOf(snowflake.nextId());
        //请求小程序接口
        List<RefundInfo> refundInfos = miniProgramInterface(orderId,refundSn);
        orderList1.setRefundSn(refundSn);
        if (CollUtil.isNotEmpty(refundInfos)) {
            refundInfos.forEach(r -> {
                int code = RefundStatus.getRefundStatus(r.getRefundStatus()).getCode();
                orderList1.setPayStatus(code);
                orderList1.setRefundTime(DateUtil.parseUTC(r.getUpdateTime()));
                orderList1.setRefundSn(r.getRefundOrderNum());
            });
        } else {
            orderList1.setPayStatus(7);
        }
        orderListMapper.update(orderList1);
    }

    /**
     * 小程序接口
     *
     * @param orderId 订单id
     * @return {@link List}<{@link RefundInfo}>
     */
    private List<RefundInfo> miniProgramInterface(String orderId,String nextId) {
        JSONObject jsonParam = new JSONObject();
        jsonParam.set("item_order_num", orderId);
        jsonParam.set("refund_order_num", nextId);
        String result = HttpUtil.get(orderUrl, jsonParam);
        log.info("小程序接口返回{}",result);
        Gson gson = new Gson();
        Map hashMap = gson.fromJson(result, HashMap.class);
        if (!hashMap.get("status").equals("pay.200")) {
            return Collections.emptyList();
        }
        try {
            RefundResult refundResult = JSON.parseObject(result, RefundResult.class);
            String payload1 = refundResult.getPayload();
            Wapper wrapper = gson.fromJson(payload1, Wapper.class);
            return wrapper.getRefundInfo();
        } catch (Exception ew) {
            log.error("退款订单格式转换失败");
        }
        return Collections.emptyList();
    }


    private void createMiniProgramOrder(Result msgResult) {
        OrderList orderList = new OrderList();
        OrderCombo orderCombo = msgResult.getOrder();

        orderList.setUserName(msgResult.getNickname());
        orderList.setUserMobile(msgResult.getMobileNumber());


        setMachineCorrelation(orderCombo, orderList);


        if (msgResult.getPaymentMethods()!=null) {
            switch (msgResult.getPaymentMethods()){
                case "WeChatPay":
                    orderList.setPayType("2");
                    break;
                case "Alipay":
                    orderList.setPayType("1");
                    break;
                default:
                    log.error("订单号:{},支付方式不匹配", msgResult.getOrder().getOrderId());
                    break;
            }
        }

        for (Detail detail : msgResult.getDetailList()) {
            if (orderCombo.getMachineId().equals(orderCombo.getUserId())){

                orderList.setAmt(detail.getDeviceAmount());

                orderList.setOrderType("1");
            }else{
                orderList.setAmt(detail.getApplietAmount());

                orderList.setOrderType("0");
            }
            orderList.setCount(Long.parseLong(detail.getCount()));

            Snowflake snowflake = new Snowflake(1);
            Combo combo = comboMapper.queryById(detail.getPackageId());
            String tagName = getTagName(combo);
            orderList.setId(detail.getOrderDetailId());
            orderList.setMachineId(orderCombo.getMachineId());
            orderList.setMachineName(orderCombo.getMachineName());
            orderList.setPayStatus(OrderStatus.getOrderStatus(orderCombo.getStatus()).getCode());
            orderList.setComboId(detail.getPackageId());
            orderList.setComboName(combo.getName());
            orderList.setComboTag(tagName);
            orderList.setUpdateTime(DateUtil.parseUTC(detail.getUpdateTime()));
            orderList.setOrderTime(DateUtil.parseUTC(detail.getCreateTime()));
            orderList.setIsExceptionOper("1");
            orderList.setPayTime(DateUtil.parseUTC(msgResult.getPayTime()));
            log.info("订单数据落库：{}", orderList);

            orderListMapper.insert(orderList);
            log.info("订单号:{},小程序订单创建成功", orderList.getOrderSn());
        }
    }

    private void setMachineCorrelation(OrderCombo orderCombo, OrderList orderList) {
        Machine machine = machineMapper.queryById(orderCombo.getMachineId());

        orderList.setCompanyId(machine.getCompanyId());
        orderList.setAreaId(machine.getAreaId());
        orderList.setRouteId(machine.getRouteId());
        orderList.setPositionId(machine.getPositionId());
        orderList.setPositionAddr(machine.getPositionAddr());
        orderList.setOrderSn(orderCombo.getOrderId());
        Area area = areaMapper.queryById(machine.getAreaId());
        if (Objects.nonNull(area)) {
            orderList.setAreaName(area.getName());
        }
        Route route = routeMapper.queryById(machine.getRouteId());
        if (Objects.nonNull(route)) {
            orderList.setRouteName(route.getName());
        }
        Position position = positionMapper.queryById(machine.getPositionId());
        if (Objects.nonNull(position)) {
            orderList.setPositionName(position.getPositonName());
        }
        Company company = companyMapper.queryById(machine.getCompanyId());
        if (Objects.nonNull(company)){
            orderList.setCompanyName(company.getName());
        }
    }

    private String getTagName(Combo combo) {
        String tagId = combo.getTagId();
        String[] tagIds = tagId.split(",");
        List<String> tagNames = Arrays.stream(tagIds).map(id -> {
            TagCombo tagCombo = tagComboMapper.queryById(id);
            return tagCombo.getTagName();
        }).toList();
        return CollUtil.isNotEmpty(tagNames) ? String.join(",", tagNames) : null;
    }

}
